package com.weixing.mall.gateway.filter;

import com.weixing.mall.base.constant.GlobalConstant;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.provider.api.service.AuthServiceRpc;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @Author: kfc
 * @Description: <br/>
 * Date:Create in 2019/9/11 14:07
 * @Modified By:
 */
@Component
@Slf4j
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<AuthGatewayFilterFactory.Config> {

    @Autowired
    @Lazy
    private AuthServiceRpc authServiceRpc;


    public AuthGatewayFilterFactory() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            String token = request.getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
            RequestPath path = request.getPath();

            if (StringUtils.isNotBlank(token) && token.startsWith(GlobalConstant.BEARER_TOKEN)) {
                // 验证token合法性，并返回用户信息
                Result<Map<String, Object>> checkToken = authServiceRpc.checkToken(StringUtils.substring(token, 7));
                if (checkToken.isSuccess()) {
                    Map<String, Object> auth = checkToken.getData();
                    boolean active = (Boolean) auth.get("active");
                    if (active) {
                        // 令牌合法，继续访问，可以进行一些处理，如：添加头信息，参数等
                        ServerHttpRequest.Builder builder = request.mutate();
                        //比如，根据令牌获得用户信息，userId
                        builder.header(GlobalConstant.X_HEADER_UR, String.valueOf(auth.get("ur")));
                        builder.header(GlobalConstant.X_HEADER_UK, String.valueOf(auth.get("uk")));
                        return chain.filter(exchange.mutate().request(builder.build()).build());
                    }
                }
            }
            return chain.filter(exchange);
        };
    }

    public static class Config {

    }
}
